import React from 'react';
import {Router, Route} from 'dva-react-router-3/router';
import Loadable from 'react-loadable';


import request from "./utils/request";

const MyLoadingComponent = ({isLoading, error}) => {
    // Handle the loading state
    if (isLoading) {
        return <div>Loading...</div>;
    }
    // Handle the error state
    else if (error) {
        return <div>Sorry, there was a problem loading the page.</div>;
    }
    else {
        return null;
    }
};

export const routeConfig = function (app) {
    return [{
        path: '/',
        // component: require('./routes/App'),
        component: Loadable({
            loader: async () => {
                let com = import('./routes/App')
                let model = await import('./models/user')
                try {
                    app.model(model)
                } catch (e) {
                }
                return com;
            },
            loading: MyLoadingComponent,
        }),
        syncData: () => {
            return request('http://localhost:3080/api/users').then(function (data) {
                return {user: data};
            });
        }
    }, {
        path: '/about',
        // component: require('./routes/About'),
        component: Loadable({
            loader: async () => {
                let com = import('./routes/About')
                let model = await import('./models/user')
                try {
                    app.model(model)
                } catch (e) {
                }
                return com;
            },
            loading: MyLoadingComponent,
        })
    }]
};
export const routes = function (app) {

    return (
        <div>
            {routeConfig(app).map((item, i) => (
                <Route key={i} path={item.path} component={item.component}/>
            ))}
        </div>
    )
};

export default function ({history, app}) {
    return (
        <Router history={history} routes={routes(app)}>
        </Router>
    );
}
